/*
 * Copyright 2011 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.orkut.androidexample;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.content.Intent;

import com.google.orkut.client.api.BatchTransaction;
import com.google.orkut.client.api.GetFriendTx;
import com.google.orkut.client.api.OrkutAdapterException;
import com.google.orkut.orkroid.Orkroid;
import com.google.orkut.orkroid.OrkroidTask;

public class ShowFriendsActivity extends ListActivity implements OrkroidTask.Listener {
	String[] friendIds = null;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setListAdapter(new ArrayAdapter<String>(this,R.layout.listitem,
				new String[] { "Loading friends..." }));
		
		try {
			BatchTransaction btx = Orkroid.getOA().newBatch();
			GetFriendTx tx = Orkroid.getOA().getFriendTF().getSelfFriends();
			tx.setCount(100);
			btx.add(tx);
			OrkroidTask.execute("", btx, this);
		}
		catch (OrkutAdapterException ex) {
			onOrkroidTaskFinished("", null, ex);
		}
	}

	public void showError(String err) {
		setListAdapter(new ArrayAdapter<String>(this,R.layout.listitem,
				new String[] { err }));
	}
	
	public void onOrkroidTaskFinished(String tag, BatchTransaction btx,
			Exception exc) {
		if (btx == null) { showError("Error requesting friends."); return; }
		if (exc != null) { showError("Error loading friends: " + exc.getMessage()); return; }
		GetFriendTx tx = (GetFriendTx) btx.getTransaction(0);
		int i;
		int count = tx.getFriendsCount();
		String[] s = new String[count];
		friendIds = new String[count];
		for (i = 0; i < count; i++) {
			s[i] = tx.getFriend(i).getDisplayName();
			friendIds[i] = tx.getFriend(i).getId();
		}
		setListAdapter(new ArrayAdapter<String>(this,R.layout.listitem,s));
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		if (friendIds == null) return;
		
		String friendId = friendIds[position];
		Intent i = new Intent(this, ShowProfileActivity.class);
		i.putExtra("userid", friendId);
		startActivity(i);
	}
}
